import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// import Home from '../src/views/Home.vue'

Vue.use(VueRouter)

const routes = [
	{
		path: '/',
		name: 'Main',
		// import 动态加载，按需引入
		component: ()=> import('views/Main.vue'),
        // 重定向到home页面 redirect: "/home"
        redirect: '/home',
		children: [
			/*{
				path: '/home',
				name: 'Home',
				// import 动态加载，按需引入
				component: ()=> import('views/home/Home.vue'),
			},
			{
				path: '/mall',
				name: 'Mall',
				// import 动态加载，按需引入
				component: ()=> import('views/mall/Mall.vue'),
			},
			{
				path: '/user',
				name: 'User',
				// import 动态加载，按需引入
				component: ()=> import('views/user/User.vue'),
			}*/
		]
	},{
        path: '/login',
        name: 'Login',
        // import 动态加载，按需引入
        component: ()=> import('views/login/Login.vue'),
    }
]

const vueRouter = new VueRouter({
    mode: 'history',
    routes
})

// 要在跳转前添加
store.commit('addMenu', vueRouter);

// 导航守卫逻辑 from:从何处来，to:到哪里
vueRouter.beforeEach((to, from, next) => {
    store.commit('getToken')
    console.log({to, from})
    const token = store.state.user.token;
    // 这里权限的逻辑就是不等于token 并且 值为login
    if (!token && to.name !== 'Login') {
        next({
            name: 'Login'
        });
    }else if(token && to.name === 'Login'){
        next({
            name: 'Home'
        });
    }else {
        next();
    }
});

// 解决路由重复单击错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err)
}



export default vueRouter
